﻿using SqlSugar;
using System;
using System.Data;

namespace SEIPropertyDataService.Entity.Converters
{
    // 适配 KingbaseES uuid <-> string
    public class KingbaseUuidConverter : ISugarDataConverter
    {
        // 数据库 -> C# 属性
        public T QueryConverter<T>(IDataRecord dataRecord, int dataRecordIndex)
        {
            var value = dataRecord.GetValue(dataRecordIndex);
            if (value is Guid guid)
            {
                // uuid -> string
                if (typeof(T) == typeof(string))
                    return (T)(object)guid.ToString("D");
                // uuid -> Guid
                if (typeof(T) == typeof(Guid))
                    return (T)value;
            }
            if (value is string str)
            {
                // uuid 也可能直接返回 string
                if (typeof(T) == typeof(string))
                    return (T)(object)str;
                if (typeof(T) == typeof(Guid) && Guid.TryParse(str, out var g))
                    return (T)(object)g;
            }
            // 其他类型直接返回
            return (T)value;
        }

        // C# 属性 -> 数据库参数
        public SugarParameter ParameterConverter<T>(object columnValue, int columnIndex)
        {
            if (columnValue is string str && !string.IsNullOrEmpty(str))
            {
                // string -> Guid
                return new SugarParameter($"@p{columnIndex}", Guid.Parse(str));
            }
            if (columnValue is Guid guid)
            {
                // Guid -> Guid
                return new SugarParameter($"@p{columnIndex}", guid);
            }
            // 其他类型
            return new SugarParameter($"@p{columnIndex}", columnValue);
        }
    }
}
